package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.ChequePenalizacion;
import ar.republicagroup.gestion.services.ChequePenalizacionServices;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.Validar;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author DIEGOALV
 */
public class modalPanelGestionRechazos extends javax.swing.JDialog {

    /*Services*/
    ChequePenalizacionServices chequePenalizacionServices  = (ChequePenalizacionServices)SpringUtils.getBean("chequePenalizacionServices");
    
     List<JTextField> requiredFieldList = new ArrayList<>();
    boolean datosValidos = false;
    
    public modalPanelGestionRechazos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        cargarDatos();
        cargarListaDeJTextFieldObligatorios();
    }

    private void cargarDatos(){
            comboEstado.setModel(chequePenalizacionServices.combo());
            lblErrorNombre.setVisible(false);
            lblErrorComision.setVisible(false);
    }
    
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        comboEstado = new javax.swing.JComboBox();
        txtNombreRechazo = new javax.swing.JTextField();
        txtComision = new javax.swing.JTextField();
        btnModificar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblErrorNombre = new javax.swing.JLabel();
        lblErrorComision = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Configurar comisiones de rechazos :..");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Comisiones de rechazos"));

        comboEstado.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboEstadoItemStateChanged(evt);
            }
        });

        txtNombreRechazo.setEditable(false);
        txtNombreRechazo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreRechazoKeyPressed(evt);
            }
        });

        txtComision.setEditable(false);

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/edit.png"))); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jLabel1.setText("Estado");

        jLabel2.setText("Nombre");

        jLabel3.setText("Comisión");

        lblErrorNombre.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorNombre.setText("(*)");

        lblErrorComision.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorComision.setText("(*)");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnModificar)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(comboEstado, 0, 208, Short.MAX_VALUE)
                            .addComponent(txtNombreRechazo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblErrorNombre))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtComision, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblErrorComision)))
                .addContainerGap(98, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombreRechazo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(lblErrorNombre))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtComision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(lblErrorComision))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnModificar)
                    .addComponent(btnCancelar))
                .addContainerGap(40, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void comboEstadoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboEstadoItemStateChanged
        if(comboEstado.getSelectedIndex() != 0){
            habilitarCampos(true);
            ChequePenalizacion estado = (ChequePenalizacion)comboEstado.getSelectedItem();
            txtNombreRechazo.setText(estado.getChequeEstadoId().getNombre());
            txtComision.setText(String.valueOf(estado.getComision()));
        } else {
            limpiarFormulario();
            habilitarCampos(false);
        }
    }//GEN-LAST:event_comboEstadoItemStateChanged

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
       actualizarEstadoDeRechazo();
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtNombreRechazoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreRechazoKeyPressed
       if(evt.getKeyCode() == KeyEvent.VK_ENTER){
           Validar.validarSiCajaDeTextoEsVacia(txtNombreRechazo.getText(), txtNombreRechazo, lblErrorNombre, txtComision, 0);
       }
    }//GEN-LAST:event_txtNombreRechazoKeyPressed

    
    private void actualizarEstadoDeRechazo(){
         if(comboEstado.getSelectedIndex() != 0){
            if(esValidoElFormulario()){
            ChequePenalizacion estadoSeleccionado = (ChequePenalizacion)comboEstado.getSelectedItem();
            estadoSeleccionado.getChequeEstadoId().setNombre(txtNombreRechazo.getText());
            estadoSeleccionado.setComision(Double.parseDouble(txtComision.getText()));
            String mensaje = chequePenalizacionServices.update(estadoSeleccionado);
            
                if(mensaje != null){
                    JOptionPane.showMessageDialog(this, mensaje, UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onUpdateError"), UIMessages.getInfoMessage("onUpdateError_title"), JOptionPane.ERROR_MESSAGE);
                }
                limpiarFormulario();
            }
        }else {
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedEstado"), UIMessages.getErrorMessage("defaultErrorTile"), JOptionPane.ERROR_MESSAGE);
        }
    }
    
    
    private void limpiarFormulario(){
        txtNombreRechazo.setText("");
        txtComision.setText("");
        cargarDatos();
    }
    
    private void habilitarCampos(boolean valor){
        txtNombreRechazo.setEditable(valor);
        txtComision.setEditable(valor);
    }
    
    
    private void cargarListaDeJTextFieldObligatorios(){
        requiredFieldList.add(txtNombreRechazo);
        requiredFieldList.add(txtComision);
    }
    
     public boolean esValidoElFormulario(){
          for(JTextField txtField : requiredFieldList){  
              if(Validar.esVacio(txtField.getText()) || Validar.validarVacio(txtField.getText())){
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredField") , UIMessages.getErrorMessage("requiredField_title"), JOptionPane.ERROR_MESSAGE);
                txtField.requestFocus();
                return false;
                }
          }
          
            if(!Validar.esUnDatoDouble(txtComision.getText())){
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("decimal"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
                return false;
            } 
         
            return true;       
    }
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                modalPanelGestionRechazos dialog = new modalPanelGestionRechazos(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JComboBox comboEstado;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblErrorComision;
    private javax.swing.JLabel lblErrorNombre;
    private javax.swing.JTextField txtComision;
    private javax.swing.JTextField txtNombreRechazo;
    // End of variables declaration//GEN-END:variables
}
